package com.itheima.easy.handler.wechat;

import com.alibaba.fastjson.JSONObject;
import com.itheima.easy.client.wechat.Config;
import com.itheima.easy.client.wechat.Factory;
import com.itheima.easy.client.wechat.response.WapPayResponse;
import com.itheima.easy.constant.SuperConstant;
import com.itheima.easy.constant.TradeConstant;
import com.itheima.easy.handler.WapPayHandler;
import com.itheima.easy.utils.EmptyUtil;
import com.itheima.easy.utils.ExceptionsUtil;
import com.itheima.easy.utils.ResponseChecker;
import com.itheima.easy.vo.TradeVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

/**
 * @ClassName WechatWapPayHandler.java
 * @Description Jsapi支付处理
 */
@Slf4j
@Component
public class WechatWapPayHandler extends WechatCommonPayHandler implements WapPayHandler {

    @Override
    public TradeVo wapTrade(TradeVo tradeVo){
        //1、获得微信客户端
        Config config = wechatPayConfig.config();
        //2、配置如果为空，抛出异常
        if (EmptyUtil.isNullOrEmpty(config)){
            throw new RuntimeException("微信支付配置为空！");
        }
        //3、指定配置文件
        Factory factory = new Factory();
        factory.setOptions(config);
        try {
            //4、调用接口
            WapPayResponse wapPayResponse = factory.Wap().pay(
                    String.valueOf(tradeVo.getTradeOrderNo()),
                    String.valueOf(tradeVo.getTradeAmount()),
                    tradeVo.getMemo(),
                    tradeVo.getOpenId());
            //5、检查网关响应结果
            boolean success = ResponseChecker.success(wapPayResponse);
            if (success&&!EmptyUtil.isNullOrEmpty(wapPayResponse.getPrepayId())){
                tradeVo.setIsRefund(SuperConstant.NO);
                tradeVo.setPlaceOrderCode(wapPayResponse.getCode());
                tradeVo.setPlaceOrderMsg(wapPayResponse.getMessage());
                tradeVo.setPlaceOrderJson(wapPayResponse.getPrepayId());
                tradeVo.setTradeState(TradeConstant.TRADE_WAIT_BUYER_PAY);
                return tradeVo;
            }else {
                log.error("网关：支付宝手机网页支付统一下单创建：{},结果：{}", tradeVo.getTradeOrderNo(),
                        JSONObject.toJSONString(wapPayResponse));
                throw new RuntimeException("网关：微信手机网页支付统一下单创建失败！");
            }
        } catch (Exception e) {
            log.error("微信手机网页支付统一下单创建失败：{}", ExceptionsUtil.getStackTraceAsString(e));
            throw new RuntimeException("微信手机网页支付统一下单创建失败");
        }
    }

}
